package com.haust.leyou.service;

import com.haust.leyou.client.UserClient;
import com.haust.leyou.config.JwtProperties;
import com.haust.leyou.pojo.User;
import com.haust.leyou.pojo.UserInfo;
import com.haust.leyou.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Auther: csp1999
 * @Date: 2020/12/20/13:32
 * @Description:
 */
@Service
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 根据用户名和密码进行认证，并获取token存入 cookie
     *
     * @param username
     * @param password
     * @return
     */
    public String accredit(String username, String password) {

        System.out.println(username + ": " + password);
        // 1.根据用户名和密码查询
        User user = userClient.queryUser(username, password);

        // 2.判断user是否为null
        if (user == null) {
            return null;
        }

        // 3.JwtUtils 生成jwt类型的token
        // 载荷userInfo
        try {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(user.getId());
            userInfo.setUsername(user.getUsername());


            return JwtUtils.generateToken(
                    userInfo,
                    jwtProperties.getPrivateKey(),
                    jwtProperties.getExpire());

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
